/*
 * GameWindow.cpp
 *
 *  Created on: May 11, 2012
 *      Author: mklingen
 */

#include "GameWindow.h"
#include <QKeyEvent>
#include <iostream>

namespace kling
{
    double count = 0.0;

    GameWindow::GameWindow(QWidget* Parent, const QPoint& Position, const QSize& Size) :
            QSFMLCanvas(Parent, Position, Size)
    {
        m_resourceManager = new kling::ResourceManager();
        kling::ImageResource* imageResource = new kling::ImageResource("axes", "assets/axes.png");
        m_resourceManager->RegisterResource("axes", imageResource);
        m_componentManager = new kling::GameComponentManager(this);
        m_testSprite = new kling::SpriteComponent("axes", m_componentManager, "Test Sprite");
        m_componentManager->AddComponent(m_testSprite);
        m_componentManager->GetRootComponent()->AddChild(m_testSprite);

        m_testSprite->SetLocalPosition(Eigen::Vector2d(300, -300));

        kling::SpriteComponent* testSprite2 = new kling::SpriteComponent("axes", m_componentManager, "Test Sprite 2");
        testSprite2->SetLocalPosition(Eigen::Vector2d(100, 100));
        testSprite2->SetLocalRotation(M_PI / 4.0);

        m_testSprite->AddChild(testSprite2);

        m_componentManager->AddComponent(testSprite2);

        m_camera = new Camera(Size.width(), Size.height());
        SetView(*(m_camera->GetView()));
    }

    GameWindow::~GameWindow()
    {
        delete m_testSprite;
        delete m_resourceManager;
        delete m_componentManager;
        delete m_camera;
    }

    void GameWindow::OnInit()
    {
        m_resourceManager->InitializeResource("axes");
        m_componentManager->Initialize();
        m_componentManager->InitializeAllComponents();
    }

    void GameWindow::Update(double dt)
    {
        count += dt;
        m_componentManager->Update(dt);
        m_camera->Update(dt);
        SetView(*(m_camera->GetView()));

        m_testSprite->SetLocalRotation(count / 10);
    }

    void GameWindow::Render(double dt)
    {
        // Clear screen
        Clear(sf::Color(50, 50, 50));
        m_componentManager->Render(dt);
    }

    void GameWindow::OnUpdate()
    {
        double dt = myTimer.interval() / 1000.0;
        Update(dt);
        Render(dt);
    }

    void GameWindow::keyReleaseEvent(QKeyEvent* keyEvent)
    {
        m_camera->HandleKeyEvent(keyEvent);
    }

    void GameWindow::keyPressEvent(QKeyEvent* keyEvent)
    {
        m_camera->HandleKeyEvent(keyEvent);
        m_componentManager->HandleKeyEvent(keyEvent);
    }

} /* namespace kling */
